package com.newbe.kaptcha.filter;

import com.newbe.kaptcha.handler.MyAuthenticationFailureHandler;
import com.newbe.kaptcha.utils.PhotoCodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @Auther: Newbe
 * @Date: 2020/4/5 20:01
 * @Description: 图片验证码过滤器
 */
@Component
public class ImageCodeFilter extends OncePerRequestFilter {

    @Autowired
    MyAuthenticationFailureHandler myAuthenticationFailureHandler;

  //3、设置验证码过滤器拦截规则
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        //不是登录请求，不校验验证码，要知道提交验证码的表单地址
        if(!"/loginFrom".equals(httpServletRequest.getRequestURI())){
            filterChain.doFilter( httpServletRequest, httpServletResponse);
        }else{
            try {
                verificationCode(httpServletRequest, httpServletResponse);
                filterChain.doFilter( httpServletRequest, httpServletResponse);
            }catch (failImageCodeException e){
                //登录失败处理器失败
                myAuthenticationFailureHandler.onAuthenticationFailure(httpServletRequest,  httpServletResponse, e);
                System.out.println("登录失败");
            }
        }
    }

    //1、自定义图片验证码校验失败异常
    public class failImageCodeException extends AuthenticationException{
        public failImageCodeException (){
            super("图片验证码校验失败");
        }
    }

    //2、验证图形验证码
    public Boolean verificationCode(HttpServletRequest request,HttpServletResponse response) throws failImageCodeException{

        Boolean codeFlag = PhotoCodeUtil.checkCode(request, response);
        //校验不通过则，抛出异常
        if (codeFlag==false){
            HttpSession session = request.getSession();
            //无论成功还是失败，客户端都应在失败的时候刷新验证码
            session.removeAttribute("vrifyCode");
            throw new failImageCodeException();
        }
       //成功
       else {
          return true;
        }

    }

}
